const http = require('../../../utils/http.js');
const tools = require('../../../utils/tools.js');

Page({
  data: {
    // 高考报名信息数据对象
    gk_exam_info: {
      exam_type: '', // 考试类型
      apply_type: '', // 报考类型
      candidate_type_code: '', // 考生类型代码
      foreign_language_test_id: 0, // 外语口语测试（0-不参加；>0表示参加的语种ID）
      promise_junior_college: 0, // 承诺报专科（0-否，1-是）
      national_special: 0, // 国家专项（0-否，1-是）
      university_special: 0, // 高校专项（0-否，1-是）
      local_special: 0, // 地方专项（0-否，1-是）
      free_medical_orientation: 0, // 免费医学定向（0-否，1-是）
      mailing_address: '', // 通知书邮寄地址
      postal_code: '', // 邮政编码
      recipient_name: '', // 收件人姓名
      recipient_phone: '', // 收件人手机号
    },
    // 下拉选项及下标
    examTypeOptions: [],
    examTypeIndex: null,
    applyTypeOptions: [],
    applyTypeIndex: null,
    candidateTypeOptions: [],
    candidateTypeIndex: null,
    foreignLanguageOptions: [],
    foreignLanguageIndex: null,
    // 语音相关
    recordedText: null,
    recording: false,
    recordFilePath: '',
    buttonText: '开始录音'
  },

  onLoad() {
    // 加载各个下拉框选项数据
    const ExamTypePromise = tools.fetchOptions("/gaokao/ExamType/all",'examTypeOptions',this)
    const ApplyTypePromise = tools.fetchOptions('/gaokao/ApplyType/all', 'applyTypeOptions', this);
    const CandidateTypePromise = tools.fetchOptions('/gaokao/CandidateType/all', 'candidateTypeOptions', this);
    const ForeignLanguagePromise = tools.fetchOptions('/foreignlanguage/list', 'foreignLanguageOptions', this);
    // 所有选项框加载完成后，加载本地数据并更新索引
    Promise.all([ExamTypePromise,ApplyTypePromise,CandidateTypePromise,ForeignLanguagePromise])
    .then(() => {
      // 尝试从本地存储获取学籍信息
      try {
        const storedInfo = wx.getStorageSync('gk_exam_info');
        if (storedInfo) {
          this.setData({ gk_exam_info: storedInfo });
          // 根据存储的ID更新下拉框选中状态
          this.updateIndexById(storedInfo);
        }
      } catch (storageError) {
        console.warn('读取本地存储失败:', storageError);
      }
    }).catch(err => {
      console.error('选项数据加载失败:', err);
      wx.showToast({
        title: '基础数据加载失败',
        icon: 'none'
      });
    });
  },

  updateIndexById(data) {
    // 根据存储的各字段 id/code/name 查找下标，更新所有下拉框默认选中状态
    this.setData({
      // 新增的考试相关选项
      examTypeIndex: tools.findIndexByCode(this.data.examTypeOptions, data.exam_type),
      applyTypeIndex: tools.findIndexByCode(this.data.applyTypeOptions, data.apply_type),
      candidateTypeIndex: tools.findIndexByCode(this.data.candidateTypeOptions, data.candidate_type),
      foreignLanguageIndex: tools.findIndexById(this.data.foreignLanguageOptions, data.foreign_language_test_id),
    });
  },

  // 下拉选择回调
  handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const index = e.detail.value;
    let valueId = '';
    if (field === 'exam_type') {
      valueId = this.data.examTypeOptions[index].code;
      this.setData({ examTypeIndex: index });
    } else if (field === 'apply_type') {
      valueId = this.data.applyTypeOptions[index].code;
      this.setData({ applyTypeIndex: index });
    } else if (field === 'candidate_type_code') {
      valueId = this.data.candidateTypeOptions[index].code;
      this.setData({ candidateTypeIndex: index });
    } else if (field === 'foreign_language_test_id') {
      valueId = this.data.foreignLanguageOptions[index].id;
      this.setData({ foreignLanguageIndex: index });
    }
    this.setData({ [`gk_exam_info.${field}`]: valueId });
  },

  // 按键选择回调（是/否）
  handleSwitchChange(e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value ? 1 : 0; // true表示"是"，false表示"否"
    this.setData({ [`gk_exam_info.${field}`]: value });
  },

  // 输入框回调
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({ [`gk_exam_info.${field}`]: e.detail.value });
  },

  // 提交高考报名信息
  handleSubmit() {
    // 提交到后端接口
    const idNumber = wx.getStorageSync('base_candidate_info').id_number;
    const postData = {
      idNumber: idNumber,
      examType: this.data.gk_exam_info.exam_type,
      applyType: this.data.gk_exam_info.apply_type,
      candidateTypeCode: this.data.gk_exam_info.candidate_type_code,
      foreignLanguageTestId: this.data.gk_exam_info.foreign_language_test_id,
      promiseJuniorCollege: this.data.gk_exam_info.promise_junior_college,
      nationalSpecial: this.data.gk_exam_info.national_special,
      universitySpecial: this.data.gk_exam_info.university_special,
      localSpecial: this.data.gk_exam_info.local_special,
      freeMedicalOrientation: this.data.gk_exam_info.free_medical_orientation,
      mailingAddress: this.data.gk_exam_info.mailing_address,
      postalCode: this.data.gk_exam_info.postal_code,
      recipientName: this.data.gk_exam_info.recipient_name,
      recipientPhone: this.data.gk_exam_info.recipient_phone
    };
    
    const fieldsToCheck = [ 'exam_type','apply_type','candidate_type_code','foreign_language_test_id',
      'promise_junior_college','national_special','university_special','local_special',
      'free_medical_orientation','mailing_address', 'postal_code','recipient_name','recipient_phone'
    ];
    const storedInfo = wx.getStorageInfoSync("gk_exam_info");
    if(tools.checkDataChanged(this.data.gk_exam_info, storedInfo, fieldsToCheck)){
      http.post("/gaokao/CandidateRegistration/upsert", postData).then(res => {
        if (res.data.code === 200) {
          // 保存到本地存储
          wx.setStorageSync('gk_exam_info', this.data.gk_exam_info);
          wx.showToast({ title: '高考报名信息更新成功', duration: 2000 });
          // 重定向到考试信息展示页面
          wx.reLaunch({
            url: '/pages/gaokao/gk_exam_registrationInfo/gk_exam_registrationInfo',
          })
        }
      }).catch(err => {
        console.error('高考报名信息更新失败:', err);
        wx.showToast({ title: '高考报名信息更新失败', icon: 'none', duration: 2000 });
      });
    }else{
      // 直接重定向到考试报名信息展示页面
      wx.reLaunch({
        url: '/pages/gaokao/gk_exam_registrationInfo/gk_exam_registrationInfo',
      })
    }
    
    
  },

  // 语音功能
  // 录音功能区
  /**
   * 切换录音状态（开始/停止录音）
   */
  toggleRecording() {
    if (this.data.recording) {
      this.setData({ recording: false });
      const recorderManager = wx.getRecorderManager();
      recorderManager.stop();
      recorderManager.onStop((res) => {
        wx.setStorageSync('recordPath', res.tempFilePath);
        this.setData({ recordFilePath: res.tempFilePath });
        this.setData({ buttonText: '开始录音' });
      });
    } else {
      tools.checkRecordPermission().then(()=>{
        this.setData({ recording: true, buttonText: '停止录音' });
        // 开始录音
        const recorderManager = wx.getRecorderManager();
        recorderManager.start({
          format: 'wav',
          duration: 60000,
          sampleRate: 44100,
          numberOfChannels: 1,
          encodeBitRate: 96000
        });
      })
      .catch(() => {
        wx.showToast({ title: err.message, icon: 'none' });
      });
    }
  },

  uploadAndRecognizeRecording() {
    if (!this.data.recordFilePath) {
      wx.showToast({ title: '请先录制录音', icon: 'none' });
      return;
    }
    const filePath = this.data.recordFilePath;
    // 调用后端识别接口
    http.asr(filePath).then(res =>{
      console.log("语音识别成功，文本如下：")
      console.log(res);
      // 根据返回的文本信息，提取其中的信息
      this.setData({ editableContent: res });
      // 调用后端的提取接口
      const postData = { "text": res };
      http.gkExtract(postData).then(res =>{
        // 处理提取后的结果
        console.log("提取后的结果，如下：")
        console.log(res)
        this.updateIdAndIndex(res.data)
      }).catch(err => {
        // 提取失败
        console.log('无法解析识别结果：', err);
        console.log('接收到的原始返回数据：', err.data);
      });
    }).catch(err =>{
      // 语音识别失败
      console.log('语音识别失败：', err);
      wx.showToast({ title: '录音识别失败', icon: 'none', duration: 2000 });
    })
  },

  // 获取了语音识别返回的结果后，对id和index进行更新
  updateIdAndIndex(dataFields){
    // 可以直接赋值的字段
    const fields = [
      "promise_junior_college","national_special","university_special","local_special","free_medical_orientation","mailing_address","postal_code","recipient_name","recipient_phone"
    ];
    // 需要进行映射的字段
    // 名称和id的映射,key为code字段，value为name字段
    const idFields={
      foreign_language_test_id:"foreign_language_test",
      exam_type: 'exam_type',
      apply_type: 'apply_type',
      candidate_type_code: 'candidate_type'
    }
    // 名称和选项映射的字段
    const arrayFields = {
      // 考试相关选项字段
      foreign_language_test_id:'foreignLanguageOptions',
      exam_type: 'examTypeOptions',
      apply_type: 'applyTypeOptions',
      candidate_type_code: 'candidateTypeOptions'
    }
      // 根据结果给字段直接赋值
      fields.forEach(key =>{
          if(!dataFields[key].includes("未知")){
              this.setData({
                  [`gk_exam_info.${key}`]:dataFields[key]
              })
          }
      })
      // 根据名字赋值code
      Object.entries(idFields).forEach(([key,value]) =>{
          // 通过两个字典的映射获取对应的值，查询id随后进行赋值
          if(!dataFields[key].includes("未知")){
            // 对考点盟市进行单独处理
            if(key == "foreign_language_test_id"){
              this.setData({
                [`gk_exam_info.${key}`]:tools.findIdByName(this.data[arrayFields[key]],dataFields[key])
              })
            }
            this.setData({
              [`gk_exam_info.${key}`]:tools.findCodeByName(this.data[arrayFields[key]],dataFields[key])
            })
          }
      })
      //更新下标
      this.updateIndexById(this.data.gk_exam_info)
  },
});